import sqlite3
import os
import uuid
from tools import *
from pm import manifest_templete


def make_notes(path: str, name: str):
    if os.path.exists(path+"/"+"notes/"+name+".ckpnotes.db"):
        wrn("pm/notes",
            f"file already exists[{path+'/'+'notes/'+name+'.ckpnotes.db'}]")
        return 1
    notes_db = sqlite3.connect(
        path+"/"+"notes/"+name+".ckpnotes.db", timeout=1)
    db_cursor = notes_db.cursor()
    info("pm/notes", "make notes")
    db_cursor.execute(manifest_templete.notes_db_temp)
    info("pm/notes", "make notes config")
    db_cursor.execute(manifest_templete.notes_config_temp)
    info("pm/notes", "set config")
    db_cursor.execute(manifest_templete.notes_set_config_temp)
    notes_db.commit()
    notes_db.close()


def open_all_notes(path: str):
    dblist = {}
    for dbs in os.listdir(path+"/"+"notes"):
        dblist[dbs.split(".")[0]] = sqlite3.connect(path+"/"+"notes/"+dbs)
    return dblist


def add_note(cursor: sqlite3.Cursor, time, types, x, y):
    return cursor.execute(manifest_templete.notes_db_add_temp,
                          {"time": time, "uuid": str(uuid.uuid1()), "types": types, "x": x, "y": y})


def save_all_notes(open_db_list: dict[sqlite3.Connection]):
    for dbs in open_db_list.values():
        dbs.commit()


def find_note(cursor: sqlite3.Cursor, froms: float, tos: float):
    return list(cursor.execute("SELECT * FROM notes WHERE time BETWEEN :froms AND :tos",
                               {"froms": froms, "tos": tos-0.000001}))
